<?php
namespace app\admin\controller;
use think\Db;
use think\Request;
use think\Controller;
use app\admin\model\Networks;
use app\admin\model\Clouds;
use app\admin\model\Messages;
use app\admin\model\Users;
use app\admin\model\Carts;
use app\admin\model\Pops;
use app\admin\model\Areas;
use app\admin\model\Orders;
use \clt\Price as PriceClt;
class Network extends Common{
	public function _initialize()
    {
        parent::_initialize();
        $this->Network = new Networks;
        $this->Cloud = new Clouds;
    }
    public function index($page=null,$key=null,$type=null,$isReport=null){
        if($this->request->isPost() || $isReport==1){
            return $this->getLists($page,$key,$this->User_id,$type,$isReport);
        }
        $this->assign('type',$type);
        $this->assign('repotUrl',U('',array('isReport'=>1)));
        $this->assign('fiels',Networks::getFields(true));
        if(Users::isCustomer($this->User_id)){
            return $this->fetch('index');
        }
         $this->assign('adminType',$this->user['group_id']);
    	return $this->fetch('handle');
    }
    public function handle($page=null,$key=null,$isReport=null){
        if($this->request->isPost() || $isReport==1){
            return $this->getLists($page,$key,0,null,$isReport);
        }

        $this->assign('repotUrl',U('',array('isReport'=>1)));
        $this->assign('fiels',Networks::getFields());

        return $this->fetch();
    }
    public function getLists($page=null,$key=null,$user_id,$type=null,$isReport=null){
        $params = $this->request->post();
        $params['isReport'] = 1;
        $page = (int)$page > 0 ? $page : 1;
        $map['is_delete'] = 0;//1是删除的网络
        $isCustomer = false;
        if(Users::isCustomer($this->User_id)){
            $map['m.user_id'] = $this->User_id;
            $isCustomer = true;
        }else if(Users::isSalesman($this->User_id) || Users::isChannel($this->User_id)){
            $userArr=[];
            Users::getCustomerSups($this->User_id,$userArr);
            $map['m.user_id'] = array('in',$userArr);
        }
        if(!empty($key)){
            $map['m.name'] = array('like',"%".$key."%");
        }
        //判断是否为客服服务
        if(!$isCustomer && !Users::isService($this->User_id)){  
            $map['m.is_sn'] = 1;  //不是客户服务需要合同号的线路
        }
        if($type == 'used'){
            $map['m.status'] = 2; //已开通
            $map['m.enddate'] = array('egt',strtotime(date('Y-m-d',time())));
        }elseif($type == 'del'){
            $map['m.status'] = 12; //已删除
        }elseif($type == 'out'){
            $map['m.status'] = 2; //已开通
            $map['m.enddate'] = array('lt',strtotime(date('Y-m-d',time())));
        }
        
        $model = $this->Network->alias('m')
            ->join('users u',"u.admin_id = m.user_id","LEFT")
            ->field('m.*,m.endcloudid as endclou,m.appro_time as approtime,m.local_cloud_id as locallabel,m.status as statuslabel,u.email,u.company,m.type as typelabel,u.email,u.address as company_address,u.tel,u.mobile')
            ->where($map)
            ->order('m.update_time desc,m.id desc');
            if($isReport == 1){  //数据要导出来
                $lists = $model->select();
                //$lists['data'] = $list;
                //$lists['total'] = count($list);
            }else{
                $lists = $model->select();
            }
        //echo $this->Network->getLastSql();    
        $data = [];
        $base = [];
        if($lists){
            foreach($lists as $k=>$vo){
                $is_renewal = 0;
                if($vo['status'] == 15 && !empty($vo['enddate'])){
                    $is_renewal = 1;
                }elseif(in_array($vo['status'], [2,8])){
                    if(!empty($vo['enddate']) && strtotime($vo['enddate']) < (time()+30*86400)){
                        $is_renewal = 1;
                    }
                }
                $vo['item'] = $k+1;
                $arr = array(
                    'id' => $vo['id'],
                    'sn'=>$vo['sn'],
                    'username'=>$vo['email'],
                    'company'=>$vo['company'],
                    'name'=>$vo['name'],
                    'locallabel'=>$vo['locallabel'],
                    'local_network' => $vo['local_network'],
                    'endclou'=>$vo['endclou'],
                    'end_network' => $vo['end_network'],
                    'broadband'=>$vo['broadband'].lang('Mbs'),
                    'daylength'=>$vo['daylength'].lang('months'),
                    'status'=>$vo['statuslabel'],
                    'enddate' => $vo['enddate'],
                    'email' => $vo['email'],
                    'company_address' => $vo['company_address'],
                    'tel' => $vo['tel'],
                    'is_renewal'=>$is_renewal,
                    'mobile' => $vo['mobile'],
                );
                if($isReport){
                    $base[] = getExportData($params['fields'],$arr);
                }
                $vo['is_renewal'] = $is_renewal;
                $vo['z_type'] = $this->Network->getTypeList($vo['endtype']);
                $data[] = $vo;
            }

        }
        if($isReport){
            $heades = getExportHeader($params['fields']);
            $this->exports($heades,$base,$params['ext']);
            exit;
        }

        return $result = ['code'=>0,'msg'=>lang('No Data...'),'data'=>$data,'count'=>count($data),'rel'=>1,''=>U('',$params)];
    }
    public function create($id=null,$form_type=null,$cart_id=null){
        if($this->request->isPost()){
            $data = $this->request->post();
            if(empty($data['name'])){
                return ['code'=>0,'msg'=>lang('Please enter the line name!')];
            }
            if((int)$data['type'] <= 0){
                return ['code'=>0,'msg'=>lang('Please select the end access type!')];
            }
            /*本端接入类 公有云*/
            if((int)$data['type'] == 3){
                if((int)$data['local_cloud_id'] <= 0){
                    return ['code'=>0,'msg'=>lang('Please choose the public cloud at this end!')];
                }
                if((int)$data['cloud_country'] <= 0){
                    return ['code'=>0,'msg'=>lang('Please choose the local cloud connection area!')];
                }
                $data['country_id'] = (int)$data['cloud_country'];
                if((int)$data['cloud_city'] <= 0){
                    return ['code'=>0,'msg'=>lang('Please select this end to access the city.')];
                }
                $data['city_id'] = (int)$data['cloud_city'];
                switch (intval($data['local_cloud_id'])) {
                    case 3739: //Google Cloud
                        // if(empty($data['AauthKey'])){
                        //     return ['code'=>0,'msg'=>lang('Please enter the Pairing key')];
                        // }
                        # code...
                        break;
                    case 3737: //AWS Cloud
                        if(empty($data['local_cloud_userid'])){
                            return ['code'=>0,'msg'=>lang('Please enter the end of the cloud account ID!')];
                        }
                        // if(empty($data['AauthKey'])){
                        //     return ['code'=>0,'msg'=>lang('Please enter the AuthKey')];
                        // }
                       
                        # code...
                        break;
                    case 3738: //Azure Cloud
                        // if(empty($data['AauthKey'])){
                        //     return ['code'=>0,'msg'=>lang('Please enter the service key')];
                        // }
                        # code...
                        break;
                    case 3742: //华为 Cloud
                        # code...
                        if(empty($data['local_cloud_userid'])){
                            return ['code'=>0,'msg'=>lang('Please enter the end of the cloud account ID!')];
                        }
                        if(empty($data['orderId1'])){
                            return ['code'=>0,'msg'=>lang('Please enter the order number.')];
                        }
                        if(empty($data['VPCID1'])){
                            return ['code'=>0,'msg'=>lang('Please enter the VPC ID.')];
                        }
                        if(empty($data['VPC1'])){
                            return ['code'=>0,'msg'=>lang('Please enter the VPC available area.')];
                        }
                        break;
                    default: //其他云
                        if(empty($data['local_cloud_userid'])){
                            return ['code'=>0,'msg'=>lang('Please enter the end of the cloud account ID!')];
                        }
                        # code...
                        break;
                }
                
            }else{ //公司机构&数据中心（私有云）
                if(intval($data['country_id']) <= 0){
                    return ['code'=>0,'msg'=>lang('Please select the local access area.')];
                }
                if((int)$data['city_id'] <= 0){
                    return ['code'=>0,'msg'=>lang('Please select this end to access the city.')];
                }
                if((int)$data['pop_id'] <= 0){
                    return ['code'=>0,'msg'=>lang('Please select this end POP.')];
                }

            }
            //本段网络必填
            if(empty($data['local_network']) || !valid_ip($data['local_network'])){
                return ['code'=>0,'msg'=>lang('Please enter the correct network!')];
            }
            /*对端数据*/
            if($data['endtype'] == 3){
                if(empty($data['endcloudid'])){
                    return ['code'=>0,'msg'=>lang('Please select the end cloud connection type!')];
                }
                if((int)$data['endcloudaddrid'] <= 0){
                    return ['code'=>0,'msg'=>lang('Please select the right end access area.')];
                }
                $data['ecountry_id'] = (int)$data['endcloudaddrid'];
                if((int)$data['ecloud_city'] <= 0){
                    return ['code'=>0,'msg'=>lang('Please select the right end access city.')];
                }
                $data['ecity_id'] = (int)$data['ecloud_city'];
                /*各个云处理方式*/
                switch (intval($data['endcloudid'])) {
                    case 3739: //Google Cloud
                        # code...
                        // if(empty($data['ZauthKey'])){
                        //     return ['code'=>0,'msg'=>lang('Please enter the Pairing key')];
                        // }
                        break;
                    case 3737: //AWS Cloud
                        if(empty($data['end_userid'])){
                            return ['code'=>0,'msg'=>lang('Please enter the end cloud account ID!')];
                        }
                        // if(empty($data['ZauthKey'])){
                        //     return ['code'=>0,'msg'=>lang('Please enter the AuthKey')];
                        // }
                       
                        # code...
                        break;
                    case 3738: //Azure Cloud
                        // if(empty($data['ZauthKey'])){
                        //     return ['code'=>0,'msg'=>lang('Please enter the service key')];
                        // }
                        # code...
                        break;
                    case 3742: //华为 Cloud
                        # code...
                        if(empty($data['end_userid'])){
                            return ['code'=>0,'msg'=>lang('Please enter the end cloud account ID!')];
                        }
                        if(empty($data['orderId2'])){
                            return ['code'=>0,'msg'=>lang('Please enter the order number.')];
                        }
                        if(empty($data['VPCID2'])){
                            return ['code'=>0,'msg'=>lang('Please enter the VPC ID.')];
                        }
                        if(empty($data['VPC2'])){
                            return ['code'=>0,'msg'=>lang('Please enter the VPC available area.')];
                        }
                        break;
                    default: //其他云
                        if(empty($data['end_userid'])){
                            return ['code'=>0,'msg'=>lang('Please enter the end cloud account ID!')];
                        }
                        # code...
                        break;
                }
            }else{
                if((int)$data['ecountry_id'] <= 0){
                    return ['code'=>0,'msg'=>lang('Please select the right end access area.')];
                }
                if((int)$data['ecity_id'] <= 0){
                    return ['code'=>0,'msg'=>lang('Please select the right end access city.')];
                }
                if((int)$data['epop_id'] <= 0){
                    return ['code'=>0,'msg'=>lang('Please select the right end to access POP.')];
                }
            }
            if(empty($data['end_network']) || !valid_ip($data['end_network'])){
                return ['code'=>0,'msg'=>lang('Please enter the correct end-to-end network!')];
            }
            if((int)$data['daylength'] <= 0){
                return ['code'=>0,'msg'=>lang('Please choose the time to buy!')];
            }
            if((int)$data['broadband'] <= 0){
                return ['code'=>0,'msg'=>lang('Please enter broadband values')];
            }
            /*其他*/
            $data['broadband'] = (int)$data['broadband'];
            $data['user_id'] = $this->User_id;
            $data['create_time'] = time();
            $data['update_time'] = date('Y-m-d H:i:s',time());
            $data['status'] = 1; //1,是申请开通
            $base = [];
            $is_send = true;
            $price = new PriceClt($data);
            $total = $price->getNetworkTotal();
            // if((int)$total <= 0){
            //     return ['code'=>0,'msg'=>lang('Service temporarily...')];
            // }
            $data['total'] = intval($total) > 0 ? intval($total) : 0;
            $data['currency'] = $price->getCurrency();
            if($id > 0){
                $this->Network = $this->Network->get($id);
                if($this->Network->pre_status == 0 || $this->Network->status==$this->Network->pre_status){
                    $is_send = false;
                }
                $data['enddate'] = $data['appro_time'] = '';
                $result = $this->Network->data($data)->allowField(true)->isUpdate(true)->save();
            }else{
                if($data['form_type'] == 1){ //购物车里面
                    $result = $this->Network->data($data)->allowField(true)->save();
                    $id = $this->Network->id;
                }else{
                    $data['_id'] = $result = Carts::addData($this->User_id,$data); //加入购物车
                    $data = $this->Network->setDataLabel($data);
                }
                $is_send = false;
            }
            if($result){
                if($is_send){
                    if($this->Network->is_sn == 1){
                        $this->notice($this->Network,$this->user['sup_id']);
                    }else{
                        $this->notice($this->Network);
                    }
                    db('network_logs')->insert(
                        array(
                            'user_id'=>$this->User_id,
                            'network_id'=>$this->Network->id,
                            'status'=>$data['status'],
                            'content'=>lang('Apply for network lines'),
                            'create_time'=>time()
                        )
                    );
                }
                return ['code'=>1,'msg'=>lang('The data has been submitted.'),'url'=>U('index'),'data'=>$data];
            }
            return ['code'=>0,'msg'=>lang('The data submission failed.')];
        }
        $this->assign('types',$this->Network->getTypeList());
        $this->assign('daLength',$this->Network->dayLength());
        $this->assign('clouds',$this->Cloud->getClouds());
        $this->assign('popArr',Pops::getPOPCountrys(0));
        $this->assign('cart_id',$cart_id);
        Carts::deleteAll($this->User_id);//删除购物车里面的
        $this->assign('carts',Carts::getCartData($this->User_id));
    	return $this->fetch();
    }
    /*修改网络线路*/
    public function edit($network_id=null,$cat=null,$cat_id=null){

        if(intval($cat_id) > 0){
            $network = Carts::getNetworkData($cat_id,$this->User_id);
            $form_type = 1;
            $network['total'] = $network['currency']." ".$network['total'];
        }else{
            $network = $this->Network->where(['id'=>$network_id])->field('*,total as free')->find();
            $form_type = 0;
        }
        if($this->request->isPost()){
               return ['code'=>1,'msg'=>'','data'=>$network]; 
        }
        if(!$network){
            return $this->error(lang('The line does not exist.'));
        }

        $this->assign('form_type',$form_type);
        $this->assign('cat',$cat);
        $this->assign('row',$network);
        $this->assign('types',$this->Network->getTypeList());
        $this->assign('popArr',Pops::getPOPCountrys(0));
        $this->assign('clouds',$this->Cloud->getClouds());
        $this->assign('daLength',$this->Network->dayLength());
        Carts::deleteAll($this->User_id,$cat_id); //删除

        return $this->fetch('edit');
    }
    public function delete($item_id=null){
        $map = array('id'=>$item_id);
        /*判断是否为客户*/
        if(Users::isCustomer($this->User_id)){
            $map['user_id'] = $this->User_id;
        }
         $Network = $this->Network->where($map)->find($item_id);
        
        if(!$Network){
            return ['code'=>0,'msg'=>lang('Network lines do not exist.')];
        }
        /*直接删除*/
        if($this->Network->where($map)->delete()){
            db('netword_products')->where(['netword_id'=>$item_id])->delete();
            return ['code'=>1,'msg'=>lang('The line has been deleted.')];
        }
        return ['code'=>0,'msg'=>lang('The operation failed, the unknown error!')];
    }
    /*申请关闭线路*/
    public function closed($item_id=null){
        $Network = $this->Network->where(array('id'=>$item_id,'user_id'=>$this->User_id))->find($item_id);
        if(!$Network){
            return ['code'=>0,'msg'=>lang('Network lines do not exist.')];
        }
        /*直接删除*/
        // if($Network->status == 1 && $this->Network->where(array('id'=>$item_id,'user_id'=>$this->User_id))->delete()){
        //     return ['code'=>1,'msg'=>lang('The line has been deleted.')];
        // }
        /*如果是正常的线路就要申请才能删除*/
        $Network->pre_status=$Network->status;
        $Network->status=12;
        $is_send = false;
        if($Network->pre_status == 2 && strtotime($Network->enddate) >= strtotime(date('Y-m-d',time()))){
            $Network->status=10;
            $is_send = true;
        }
        if($Network->save() !== false){
            db('network_logs')->insert(
                    array(
                        'user_id'=>$this->User_id,
                        'network_id'=>$item_id,
                        'status'=>$Network->status,
                        'content'=>lang('Delete network lines'),
                        'create_time'=>time()
                    )
            );
            /*在正常的使用的网络线路才申请发送通知*/
            if($is_send){
                $this->notice($Network);
                return ['code'=>1,'msg'=>lang('Application has been submitted, please wait for confirmation.')];
                //Messages::Notice($this->user['sup_id'],lang('网络线路删除申请通知'),lang('有客户申请删除【'.$Network['name'].'】网络线路，请及时查询并且确认。'),2,false);
            }
            return ['code'=>1,'msg'=>lang('The line has been closed.')];
        }
        return ['code'=>0,'msg'=>lang('The operation failed, the unknown error!')];
    }
    /**/
    public function view($network_id=null){
        $row = $this->Network->where('id',$network_id)->field('*,local_cloud_id as locallabel,endcloudid as endclou,type as locatlabeladdress,status as statuslabel,type as typelabel,appro_time as approtime,endtype as endlabeladdress')->find();
        if(!$row){
            return $this->error(lang('The network line information does not exist.'));
        }
        $row = $row->toArray();

        $this->assign('adminType',$this->user['group_id']);
        
        $user = !Users::isCustomer($this->User_id) ? Users::getUserInfo($row['user_id']) : '';
        $this->assign('user',$user);
        $config = [];
        $config = db('network_config')->where(array('network_id'=>$row['id']))->find();//管理员可以编辑配置信息
        $this->assign('enginees',Users::getEngineers());
        $this->assign('config',$config);
        $this->assign('engStatus',Networks::getEngStatus($row['id'],$row['status']));
        $this->assign('backeens',Networks::backeens($row['id']));//0没有分配，1分配，2已反馈
        $this->assign('checkEngHasPsiee',Networks::checkEngHasPsiee($row['id'],$this->User_id));
        $this->assign('statuslist',$this->Network->getStatuslabelAttr());
        $isAuto = 0;
        /*公有云*/
        if(($row['type'] == Networks::NETWORK_TYPE_3 || $row['endtype'] == Networks::NETWORK_TYPE_3) && $row['status'] == 1){
            if($row['type'] == Networks::NETWORK_TYPE_3 && $row['country_id'] != Areas::CHINA_ID){
                $isAuto = 1;
            }
            if($row['endtype'] == Networks::NETWORK_TYPE_3 && $row['ecountry_id'] != Areas::CHINA_ID){
                $isAuto = 1;
            }
        }
        /*数据中心*/
        if(($row['type'] == Networks::NETWORK_TYPE_2 && $row['endtype'] == Networks::NETWORK_TYPE_2) && $row['status'] == 1){
            if($row['type'] == Networks::NETWORK_TYPE_2 && $row['country_id'] != Areas::CHINA_ID && $row['ecountry_id'] != Areas::HK_ID){
                $isAuto = 1;
            }
            if($row['endtype'] == Networks::NETWORK_TYPE_2 && $row['ecountry_id'] != Areas::CHINA_ID && $row['ecountry_id'] != Areas::HK_ID){
                $isAuto = 1;
            }
        }
        $row['z_type'] = $this->Network->getTypeList($row['endtype']);
        $this->assign('row',$row);
        $this->assign('typeLabel',$this->Network->getTypeList());
        $this->assign('isAuto',$isAuto);
        return $this->fetch('view2');
    }
    /*重新开通*/
    public function rekaiton($network_id=nul){
        $nework = $this->Network->get($network_id);
        if(!$nework){
            return ['code'=>0,'msg'=>lang('Network lines do not exist.')];
        }
        $nework->pre_status = $nework->status;
        $nework->status = 1;//重新开通
        $nework->update_time = date('Y-m-d H:i:s',time());
        if($nework->save()){
             Messages::Notice($nework['user_id'],lang('Notifications for application of network lines'),lang('Customers apply for the opening of network lines. Please check and confirm in time.'));
            db('network_logs')->insert(
                array(
                    'user_id'=>$this->User_id,
                    'network_id'=>$network_id,
                    'status'=>$nework->status,
                    'content'=>lang('Confirm the opening of network lines'),
                    'create_time'=>time()
                )
            );
            return ['code'=>1,'msg'=>lang('The application has been submitted.')];
        }
        return ['code'=>0,'msg'=>lang('Failure to apply for submission.')];
    }
    /*审批通过*/
    public function _confirm($nework_id=null){
        if($this->request->isPost()){            
            $nework = $this->Network->get($nework_id);
            if(!$nework){
                return ['code'=>0,'msg'=>lang('Network lines do not exist.')];
            }
            $nework->pre_status = $nework->status;
            $type = 1;
            if($nework->status == 8){  //寬帶調整
                $mbps =  $nework->broadband;
                $nework->broadband = $nework['mbs'];
                $nework->mbs = $mbps;
                $price = new PriceClt($nework->toArray());
                $total = $price->getNetworkTotal();
                $nework->total = intval($total) > 0 ? intval($total) : 0;
                $nework->currency = $price->getCurrency();
                $type=2;
            }else{
                $plan_time = 0;
                if(!empty($nework['plan_time'])){
                    $plan_time = strtotime($nework['plan_time']);
                }
                $nework->appro_time = $plan_time > time() ? $plan_time : time();//設置開通時間
                $nework->aliy_time = time(); //審批時間
                $nework->enddate = strtotime("+".$nework['daylength']." month",strtotime($nework->appro_time)); //到期时间
            }
            $nework->update_time = date('Y-m-d H:i:s',time());
            $nework->status = 2;
            if($nework->save() !== false){
                /*结束流程*/
                db('network_enginee')->where(['network_id'=>$nework->id,'is_update'=>0])->update(['is_update'=>1,'update_time'=>time()]);
                $nework->engineeId = Networks::lastEngId($nework->id);
                $this->notice($nework);
                db('network_logs')->insert(
                    array(
                        'user_id'=>$this->User_id,
                        'network_id'=>$nework_id,
                        'status'=>$data['status'],
                        'content'=>lang('Confirm the application of the network line'),
                        'create_time'=>time()
                    )
                );
                //订单订阅
                Orders::add($nework->id,$this->User_id,$type); 
                return ['code'=>1,'msg'=>lang('The data was submitted successfully.')];
            }
        }
        return ['code'=>0,'msg'=>lang('The operation failed, the unknown error!')];
    }
    /*审核驳回*/
    public function _backtask($nework_id=null){
        if($this->request->isPost()){
            $data = $this->request->post();
            if(empty($data['desc'])){
                return ['code'=>0,'msg'=>lang('Please enter the return reasons.')];
            }
            $nework = $this->Network->get($nework_id);
            if(!$nework){
                return ['code'=>0,'msg'=>lang('Network lines do not exist.')];
            }
            $status = $nework->status;
            if($nework->status == 1){
                $nework->status = 4;
            }elseif($nework->status == 8){ //调整中
                $nework->status = 2;
            }
            $nework->update_time = date('Y-m-d H:i:s',time());
            $nework->pre_status = $status;
            if($nework->save() !== false){
                $nework->desc = $data['desc'];
                $nework->status = 4;
                $this->notice($nework);
                db('network_logs')->insert(
                    array(
                        'user_id'=>$this->User_id,
                        'network_id'=>$nework_id,
                        'status'=>$nework->status,
                        'content'=>lang('Application of network route back'),
                        'create_time'=>time(),
                        'desc'=>$data['desc']
                    )
                );
                return ['code'=>1,'msg'=>lang('The data was submitted successfully.')];
            }
        }
        return ['code'=>0,'msg'=>lang('The operation failed, the unknown error!')];
    }
    /*确认删除*/
    public function confirmdel($nework_id=null){
        if($this->request->isPost()){
            $nework = $this->Network->get($nework_id);
            if(!$nework){
                return ['code'=>0,'msg'=>lang('Network lines do not exist.')];
            }
            $nework->pre_status = $nework['status'];
            $nework->status = 12;
            if($nework->save()){
                $this->notice($nework);
                db('network_logs')->insert(
                    array(
                        'user_id'=>$this->User_id,
                        'network_id'=>$nework_id,
                        'status'=>$nework->status,
                        'content'=>lang('Network line confirmation deletion'),
                        'create_time'=>time()
                    )
                );
                return ['code'=>1,'msg'=>lang('The network line has been deleted.')];
            }
        }
        return ['code'=>0,'msg'=>lang('The operation failed, the unknown error!')];
    }
    /*退回删除申请*/
    public function _backdel($nework_id=nul){
        if($this->request->isPost()){
            $data = $this->request->post();
            if(empty($data['desc'])){
                return ['code'=>0,'msg'=>lang('Please enter the return reasons.')];
            }
            $nework = $this->Network->get($nework_id);
            if(!$nework){
                return ['code'=>0,'msg'=>lang('Network lines do not exist.')];
            }
            $status = $nework->status;
            $nework->status = $nework->pre_status;
            $nework->pre_status = $status;
            $nework->update_time = date('Y-m-d H:i:s',time());
            if($nework->save() !== false){
                $nework->status = 14;
                $nework->desc = $data['desc'];
                $this->notice($nework);
                db('network_logs')->insert(
                    array(
                        'user_id'=>$this->User_id,
                        'network_id'=>$nework_id,
                        'status'=>$data['status'],
                        'content'=>lang('Network line deletion application return'),
                        'create_time'=>time()
                    )
                );
                return ['code'=>1,'msg'=>lang('The data was submitted successfully.')];
            }
        }
        return ['code'=>0,'msg'=>lang('The operation failed, the unknown error!')];
    }
    /*放回垃圾箱*/
    public function dustbin($id=null){
        if($id>0 && $this->Network->where('id',$id)->update(array('is_delete'=>1))){
            return ['code'=>1,'msg'=>lang('Data has been deleted')];
        }
        return ['code'=>0,'msg'=>lang('Delete data failure')];
    }
    /*调整线路*/
    public function update($network_id=null,$mbs=null){
        $map['status'] = 2;
        $map['enddate'] = array('egt',strtotime(date('Y-m-d',time())));
        $map['is_delete'] = 0;
        $map['id'] = (int) $network_id;
        $network = $this->Network->where('id',$network_id)->field('*,local_cloud_id as locallabel,endcloudid as endclou,type as locatlabeladdress,status as statuslabel,type as typelabel,appro_time as approtime,endtype as endlabeladdress')->find();
        if(!$network){
            $this->error(lang('The line does not exist.'));
        }
        if($this->request->post()){
            $mbs = (int)$mbs;
            if($mbs <= 0 || $mbs > 2000){
                return ['code'=>0,'msg'=>lang('The input network broadband is not right.')];
            }
            if($mbs == $network['broadband']){
                return ['code'=>0,'msg'=>lang('The bandwidth has not changed.')];
            }
            $base = $network->toArray();
            $network->mbs =$mbs;
            $network->pre_status = $network->status;
            $network->status =8;
            $network->update_time = date('Y-m-d H:i:s',time());
            if($network->save() !== false){
                $this->notice($network);
                db('network_logs')->insert(
                    array(
                        'user_id'=>$this->User_id,
                        'network_id'=>$network_id,
                        'status'=>$network->status,
                        'content'=>lang('Application for broadband adjustment of network lines'),
                        'create_time'=>time(),
                        'old_data' =>serialize($base)
                    )
                );
                return ['code'=>1,'msg'=>lang('Broadband adjustment for network lines has been submitted.'),'url'=>U('index')];
            }
            return ['code'=>0,'msg'=>lang('Network line broadband adjustment submission failed.')];
        }
        $mb = $network['broadband'] < 0 ? 1 : $network['broadband'];
        $mb = $mb > 2000 ? 2000 : $mb;
        $this->assign('row',$network);
        $this->assign('mb',$mb);
        return $this->fetch();
    }
    public function exports($heades,$data,$ext='xlsx'){
        return parent::export('CloudFast',$heades,$data,$ext);
    }
    /*重置合同编号*/
    public function resetsn($network_id=null){
        $network = $this->Network->where('id',$network_id)->field('*,status as statuslabel')->find();
        if(!$network){
            return $this->error(lang('The network line information does not exist.'));
        }
        if($this->request->isPost()){
            $data = $this->request->post();
            if(empty($data['value'])){
                return ['code'=>0,'msg'=>lang('Please enter the contract number')];
            }
            $network->is_sn = 1;
            $network->sn = $data['value'];
            $network->update_time = date('Y-m-d H:i:s',time());
            if($network->save() !== false){
                if($network->status == 1){
                    $sup_id = Users::getSupId($network->user_id);
                    $this->notice($network,1);
                }
                return ['code'=>1,'msg'=>lang('Contract number reset success.')];
            }
            return ['code'=>0,'msg'=>lang('Unknown error, please reenter it.')];
        }
        $this->assign('row',$network);
        return $this->fetch();
    }   
    /*保存配置信息*/
    public function saveConfig($network_id=null){
        if($this->request->isPost()){
            $network = $this->Network->where('id',$network_id)->find();
            if(!$network){
                return ['code'=>0,'msg'=>lang('The network line information does not exist.')];
            }
            $data = $this->request->post();
            $result = db('network_config')->insert($data,true);
            if($result){
                 return ['code'=>1,'msg'=>lang('The data is saved successfully!')];
            }
        }
        return ['code'=>0,'msg'=>lang('Data save failed!')];
    }
    /*查询价格*/
    public function query($network_id=null,$auto=null,$mbs=null,$daylength=null){
        if($this->request->isPost()){
            
            if(intval($auto) == 1 && intval($network_id) > 0){
                $data = db('networks')->where(['id'=>$network_id])->find();
                $data['broadband'] = $mbs;
            }elseif(intval($auto) == 2 && intval($network_id) > 0){ //续期
                $data = db('networks')->where(['id'=>$network_id])->find();
                $data['daylength'] = $daylength;
            }else{
                $data = $this->request->post();
                if((int)$data['type'] == 3){
                    $data['country_id'] = (int)$data['cloud_country'];
                    $data['city_id'] = (int)$data['cloud_city'];
                }
                if($data['endtype'] == 3){
                    $data['ecountry_id'] = (int)$data['endcloudaddrid'];
                    $data['ecity_id'] = (int)$data['ecloud_city'];
                }
            }
            $price = new PriceClt($data);
            $total = $price->getNetworkTotal();
            if($total === -1){ //请求失败
                 return ['code'=>-1,'msg'=>"<span class='price-money'>".lang('Request error')."</span>",'total'=>0,'currency'=>''];
            }
            if($total === -2){ //不支持的线路
                 return ['code'=>-1,'msg'=>"<span class='price-money'>".lang('No service provided')."</span>",'total'=>0,'currency'=>''];
            }
            if($total !== false && $total > 0){
                $total = _discount($total);
                return ['code'=>1,'msg'=>lang('Configuration Cost:')."<span class='price-money'>".prefix_free(intval($total))." / ".lang('Month')."</span>",'total'=>intval($total),'currency'=>$price->getCurrency()];
            }
            return ['code'=>0,'msg'=>"<span class='price-money'>-- / ".lang('Month')."</span>",'total'=>0,'currency'=>''];
        }
        $isCustomer = 0;
        if(Users::isCustomer($this->User_id)){
            $isCustomer = 1;
        }
        $this->assign('types',$this->Network->getTypeList());
        $this->assign('daLength',$this->Network->dayLength());
        $this->assign('clouds',$this->Cloud->getClouds());
        $this->assign('popArr',Pops::getPOPCountrys(0));
        $this->assign('isCustomer',$isCustomer);
        return $this->fetch('price');
    }
    /*续期*/
    public function renewal($netword_id=null,$daylength=null,$total=null){
        $map['id'] = (int) $network_id;
        $network = $this->Network->where('id',$netword_id)->field('*,local_cloud_id as locallabel,endcloudid as endclou,type as locatlabeladdress,status as statuslabel,type as typelabel,appro_time as approtime,endtype as endlabeladdress')->find();
        if(!$network){
            $this->error(lang('The line does not exist.'));
        }

        if($this->request->post()){
            if(intval($daylength) <= 0){
                return ['code'=>0,'msg'=>lang('Please choose the renewal time.')];
            }
            if($network['status'] != 2 && $network['status'] != 8 && $network['status'] != 15){
                $this->error(lang('The line is in abnormal condition.').$network['status']);
            }
            $base = $network->toArray();
            $network->pre_status = $network->status;
            if($network->status == 15){
                $network->enddate = strtotime("+".$daylength." month",strtotime(date('Y-m-d',time()))-86400); //到期时间
                $network->status = 2;
            }else{
                $network->enddate = strtotime("+".$daylength." month",strtotime($network->enddate)-86400); //到期时间
            }
            $network->total = $total;
            $network->update_time = date('Y-m-d H:i:s',time());
            if($network->save() !== false){
                $network->status = 20;
                $this->notice($network);
                db('network_logs')->insert(
                    array(
                        'user_id'=>$this->User_id,
                        'network_id'=>$netword_id,
                        'status'=>15,
                        'content'=>lang('Route renewal confirmation'),
                        'create_time'=>time(),
                        'old_data' =>serialize($base)
                    )
                );
                //订单订阅
                Orders::add($base['id'],$this->User_id,4); 
                return ['code'=>1,'msg'=>lang('Successful line renewal'),'url'=>U('index')];
            }
            return ['code'=>0,'msg'=>lang('Data save failed!')];
        }
        $mb = $network['broadband'] < 0 ? 1 : $network['broadband'];
        $mb = $mb > 2000 ? 2000 : $mb;
        $this->assign('row',$network);
        $this->assign('mb',$mb);
        $this->assign('daLength',$this->Network->dayLength());
        return $this->fetch();
    }
}